package cn.didi.feidi.androidorder.fragment;

import android.Manifest;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.google.gson.reflect.TypeToken;

import java.util.HashMap;

import cn.didi.feidi.androidorder.R;
import cn.didi.feidi.androidorder.api.Api;
import cn.didi.feidi.androidorder.api.ApiResponse;
import cn.didi.feidi.androidorder.api.ErrorEvent;
import cn.didi.feidi.androidorder.core.ActionCallbackListener;
import cn.didi.feidi.androidorder.core.AppActionRequest;
import cn.didi.feidi.androidorder.databinding.FragmentShowDeliverLocationBinding;
import cn.didi.feidi.androidorder.manager.UserManager;
import cn.didi.feidi.androidorder.model.OrderUser;
import cn.didi.feidi.androidorder.model.Position;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.RuntimePermissions;

/**
 * Created by jinxiong on 2017/8/30.
 */

@RuntimePermissions
public class ShowDeliverLocationFragment extends BaseMapFragment {

    private static final String TAG = "ShowDeliverLocationFrag";
    //  暂时设置为2秒，后面设置至少为10秒
    private final static int TIME_INTERVAL = 2000; //单位 秒 获取送水工的位置 时间间隔
    private final static int GET_LOCATION_AGAIN_FLAG = 2; // 再次请求送水工位置
    protected LatLng locationLatLng;//定位到的位置
    protected Marker locationMarker;//用户定位位置
    OrderUser orderUser;
    FragmentShowDeliverLocationBinding binding;
    private Marker deliverLocationMarker;//送水工位置
    private HashMap<String, String> parameters = new HashMap<>();
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {

                case GET_LOCATION_AGAIN_FLAG: {
                    getDeliverLocation();
                    Log.d(TAG, "handleMessage: handler");

                    break;
                }
            }
        }
    };

    /**
     * 与activity关联，后面可考虑单例模式
     *
     * @param bundle
     * @return
     */
    public static ShowDeliverLocationFragment newInstance(Bundle bundle) {
        ShowDeliverLocationFragment fragment = new ShowDeliverLocationFragment();
        if (bundle != null)
            fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        orderUser = (OrderUser) getActivity().getIntent().getSerializableExtra("orderUser");
    }

    @Override
    protected View initFragment(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_show_deliver_location, container, false);
        mMapView = binding.mapView;
        binding.mapView.onCreate(savedInstanceState);
        return binding.getRoot();
    }

    @Override
    protected void initViews(View rootView) {

    }


    @Override
    protected void initData() {
        ShowDeliverLocationFragmentPermissionsDispatcher.getPermissionBlankMethodWithCheck(this);
        initMapLocation();
        mClient.startLocation();
        Toast.makeText(mActivity, "开启定位", Toast.LENGTH_SHORT).show();

        //获取送水工位置
        getDeliverLocation();
    }


    /**
     * 获取送水工位置
     */
    private void getDeliverLocation() {

        parameters.put("userId", UserManager.getUserId());
        parameters.put("token", UserManager.getToken());
        parameters.put("waterDeliverId", orderUser.getWaterDeliverId());
        executeRequest(new AppActionRequest<>(Api.GET_WATER_DELIVER_POSITION, parameters, new TypeToken<ApiResponse<Position>>() {
        }.getType(), new ActionCallbackListener<Position>() {
            @Override
            public void onSuccess(String message, Position position) {


                if (position == null) {

                } else {

                    if (deliverLocationMarker != null) {
                        deliverLocationMarker.remove();
                    }

                    LatLng deliverLocation = new LatLng(position.getLatitude(), position.getLongitude());
//                    mAMap.moveCamera(CameraUpdateFactory.newLatLngZoom(deliverLocation, 15));
                    deliverLocationMarker = mAMap.addMarker(new MarkerOptions().position(deliverLocation).title("送水工").icon(BitmapDescriptorFactory.fromResource(R.drawable.deliver_location)));

                }


                handler.sendEmptyMessageDelayed(GET_LOCATION_AGAIN_FLAG, TIME_INTERVAL);
            }

            @Override
            public void onFailure(int errorEvent, String message) {

                if (errorEvent == ErrorEvent.PARAM_ACCESS_ERROR_NET) {
                    Toast.makeText(mActivity, "网络出现问题", Toast.LENGTH_SHORT).show();
                }

                Log.d(TAG, "onFailure: " + message);

                handler.sendEmptyMessageDelayed(GET_LOCATION_AGAIN_FLAG, TIME_INTERVAL);
            }
        }).setEmergency(true));


    }

    private void initMapLocation() {
        mAMap = binding.mapView.getMap();
        mOption.setOnceLocationLatest(true);//只定位一次
        mOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);//高精确模式
        mClient.setLocationOption(mOption);
        mClient.setLocationListener(this);
    }

    @Override
    protected void addListener() {

    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (null != aMapLocation) {

            Bundle bundle = aMapLocation.getExtras();

            if (bundle != null) {

                int errorCode = bundle.getInt(MyLocationStyle.ERROR_CODE);
                String errorInfo = bundle.getString(MyLocationStyle.ERROR_INFO);
                int locationType = bundle.getInt(MyLocationStyle.LOCATION_TYPE);

                Log.d(TAG, "onLocationChanged: error" + errorCode + "   errorInfo  " + errorInfo +
                        "  locationType  " + locationType);

                locationLatLng = new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude());

                mAMap.moveCamera(CameraUpdateFactory.newLatLngZoom(locationLatLng, 15));
                locationMarker = mAMap.addMarker(new MarkerOptions().position(locationLatLng).icon(BitmapDescriptorFactory.fromResource(R.drawable.user_location)));

//                Animation animation = new RotateAnimation(deliverLocationMarker.getRotateAngle(),deliverLocationMarker.getRotateAngle()+180,0,0,0);
//                long duration = 1000L;
//                animation.setDuration(duration);
//                animation.setInterpolator(new LinearInterpolator());
//
//                deliverLocationMarker.setAnimation(animation);
//                deliverLocationMarker.startAnimation();
            } else {
                Log.d(TAG, "onLocationChanged: " + aMapLocation.getErrorInfo());

                Log.d(TAG, "onLocationChanged: bundle null");
            }


        } else {
            Log.d(TAG, "onLocationChanged: 定位失败");
        }

    }

    @NeedsPermission({Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION})
    @Override
    protected void getPermissionBlankMethod() {

    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        handler.removeCallbacksAndMessages(null);
    }
}
